import axios from "axios";
import React, { useEffect, useState } from "react";
import { Search, Swiper, Grid, List } from "react-vant";
import { ListItem } from "../../components";
import { useNavigate } from "react-router-dom";
interface MenuType {
  id: number;
  image: string;
  title: string;
}

export interface ListType {
  id: string;
  title: string;
  word: string;
  images: string[];
  price: number;
}

const Index: React.FC = () => {
  const [banners, setBanners] = useState<string[]>([]);
  const [menus, setMenus] = useState<MenuType[]>([]);
  const [lists, setLists] = useState<ListType[]>([]);
  const [pageCode, setPageCode] = useState(1);
  const navigate = useNavigate()
  const fetchBanners = async () => {
    const resp = await axios.get("/api/banners");
    setBanners(resp.data.data);
  };
  const fetchMenus = async () => {
    const resp = await axios.get("/api/menus");
    setMenus(resp.data.data);
  };
  const fetchLists = async () => {
    const resp = await axios.get("/api/lists", { params: { pageCode } });
    setLists([...lists, ...resp.data.data]);
  };

  useEffect(() => {
    fetchBanners();
    fetchMenus();
  }, []);

  useEffect(() => {
    fetchLists();
  }, [pageCode]);

  return (
    <div>
      <Search placeholder="请搜索内容"></Search>
      {banners.length && (
        <Swiper>
          {banners.map((v, i) => {
            return (
              <Swiper.Item key={i}>
                <img src={v} alt="" style={{ width: "100%" }} />
              </Swiper.Item>
            );
          })}
        </Swiper>
      )}
      {menus.length && (
        <Grid columnNum={5} border={false}>
          {menus.map((v, i) => {
            return (
              <Grid.Item
                key={i}
                icon={<img src={v.image} alt="" width={30} />}
                text={v.title}
              ></Grid.Item>
            );
          })}
        </Grid>
      )}

      <List onLoad={async () => setPageCode(pageCode + 1)} finished={false}>
        {lists.length &&
          lists.map((v) => {
            return (
              <ListItem key={v.id} { ...v } onClick={() => navigate('/detail/' + v.id)}></ListItem>
            );
          })}
      </List>
    </div>
  );
};

export default Index;
